package com.lee.bemorebetter.algo.learn.array;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * 1) 数组的插入、删除、按照下标随机访问操作；
 * 2）数组中的数据是int类型的；
 * @author ：liylw
 * @date ：Created in 2021/3/25 10:43
 */
@Slf4j
public class Array {

    public int[] data;
    private int n;
    private int count;


    public Array(int capacity) {
        this.data = new int[capacity];
        this.n = capacity;
        this.count = 0;
    }

    /**
     * 根据下标返回数据
     * @author liylw
     * @date  2021/3/25 11:05
     * @param index 下标
     * @return int
     */
    public int get(int index){
        if (index<0 || index>=count){
            throw new ArrayIndexOutOfBoundsException();
        }
        return data[index];
    }


    /***
     * 插入
     * @author liylw
     * @date  2021/3/25 13:44
     * @param index 指定位置
     * @param value 数值
     * @return boolean
     */
    public boolean insert(int index,int value){
        if (index<0 || index>count){
            return false;
        }
        if (count == n){
            log.info("数组满了");
            return false;
        }
        System.arraycopy(data, index, data, index + 1, count - index);
        data[index] = value;
        count++;
        return true;
    }


    public boolean delete(int index){
        if (index<0 || index>=count){
            return false;
        }

        System.arraycopy(data,index+1,data,index,count-index);
        count--;
        return true;
    }

    @Override
    public String toString() {
        return "Array{" +
                "data=" + Arrays.toString(data) +
                ", n=" + n +
                ", count=" + count +
                '}';
    }



    public static void main(String[] args) {
        Array array = new Array(6);
        array.insert(0,1);
        array.insert(1,2);
        array.insert(2,3);
        log.info(array.toString());
        array.delete(2);
        log.info(array.toString());

        array.delete(0);
        log.info(array.toString());

        array.delete(0);
        log.info(array.toString());

    }
}
